<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Models\Lesson;
use App\Http\Models\Course;

//引入验证类
use Illuminate\Support\Facades\Validator;
//引入storage 类
use Illuminate\Support\Facades\Storage;




class LessonController extends Controller
{
    public function index(Request $request){
        if($request->isMethod('post')){
            //获取课时列表信息
            $cnt  = Lesson::count();

            //数据分页信息
            //偏移量(第几页)
            $offset = $request->input('start');
            //显示数据的条数
            $len = $request->input('length');

            //进行排序的数据
            $n =  $request->input('order.0.column');//获取进行排序字段的列号
            $ofield = $request->input('columns.'.$n.'.data');//获取进行排序的字段
            $order = $request->input('order.0.dir');//进行排序的顺序（asc|desc）

            //进行模糊检索的数据
            $searchVal = $request->input('search.value');//获取进行模糊查询的数据
            $data = Lesson::offset($offset)
                ->limit($len)
                ->orderBy($ofield,$order)
                ->where('lesson_name','like',"%$searchVal%")
                ->orWhere('lesson_desc','like',"%$searchVal%")
                ->with(['course'=>function($c){//渴求时加载 course表  再通过course表加载profession表
                    $c->with('profession');
                }])
                ->get();
            //datatable 需要返回的数据格式
            $info = [
                'draw'=>$request->input('draw'),
                'recordsTotal'=>$cnt,
                'recordsFiltered'=>$cnt,
                'data'=>$data
            ];
            return $info;
        }

        return view('admin.lesson.lesson');
       
    }
    public function add(Request $request){
        if($request->isMethod('post')){
            $form_data = $request->all();
            
            //数据校验
            $rules = [
                'lesson_name'=>'required',
                'lesson_duration'=>['required','regex:/^[1-9]|[1-9]\d$/'],
                'teachers'=>'required',
                'video_address'=>'required'
            ];
            $notices = [
                'lesson_name.required'=>'课程名称不能为空',
                'lesson_duration.required'=>'课时时长不能为空',
                'lesson_duration.regex'=>'课时时长不能超过100分钟',
                'teachers.required'=>'授课老师不能为空',
                'video_address.required'=>'视频不能为空'
            ];
            //制作校验
            $validator = Validator::make($form_data,$rules,$notices);

            if($validator->passes()){
                //上传的教师id是一个数组 存储时以json数据存储
                $form_data['teacher_ids'] = json_encode($form_data['teachers']);
                //校验通过
                //模拟现在没法添加的数据
                // $form_data['course_id'] = 3;
                // $form_data['cover_img'] = 'caibi.png';
                // $form_data['video_address'] = 'caibi.mp4';
                // $form_data['teacher_ids'] = 10;
                //批量赋值
                Lesson::create($form_data);
                return ['success'=>true];
            }else{
                //校验不通过
                //将错误信息一块输出 （详见辅助函数）
                $errorInfo = collect($validator->messages())->implode('0','|');
                //验证的错误信息是一个数组
                // $errorInfo = json_encode($validator->messages());
                // dd($errorInfo);
                return ['success'=>false,'errorinfo'=>$errorInfo];
            }
        }
        $course = Course::pluck('course_name','course_id');
        //pluck()  第一个参数为值 第二个为键
        $teacher = \DB::table('teacher')->pluck('teacher_name','teacher_id');
        // dd($teacher);
        return view('admin.lesson.add',compact('course','teacher'));
    }
    //播放视频
    public function video_play(Request $request,Lesson $lesson){

        return view('admin.lesson.video_play',compact('lesson'));
    }

    //修改课时信息
public function edit(Request $request,Lesson $lesson){
    //取出teacher_ids 格式化
    $lesson['teacher_ids']=json_decode($lesson['teacher_ids']);
//    dd($lesson['teacher_ids']);
    //取出课程名称和id
    $course = \DB::table('course')->pluck('course_name','course_id');
    //取出教师的名字和ID
    $teacher = \DB::table('teacher')->pluck('teacher_name','teacher_id');
    if($request->isMethod('post')){
        $form_data = $request->all();
        //数据校验
        $rules = [
            'lesson_name'=>'required',
            'lesson_duration'=>['required','regex:/^[1-9]|[1-9]\d$/'],
            'teachers'=>'required',
            'video_address'=>'required',
            'lesson_desc'=>'required'
        ];
        $notices = [
            'lesson_name.required'=>'课程名称不能为空',
            'lesson_duration.required'=>'课时时长不能为空',
            'lesson_duration.regex'=>'课时时长不能超过100分钟',
            'teachers.required'=>'授课老师不能为空',
            'video_address.required'=>'视频不能为空',
            'lesson_desc.required'=>'课时介绍不能为空'
        ];
        
        //制作校验
        $validator = Validator::make($form_data,$rules,$notices);
        //当数据验证成功时
        if($validator->passes()){

            //判断修改的图片路径和数据库中的图片路径是否一致（不一致则删除）
            if($form_data['cover_img'] !=$lesson->cover_img){
                //判断删除文件是否存在
                if(file_exists('.'.$lesson->cover_img)){//l路径为 /storage/cover/Riv8jSTNs8EWqAvuBCPpI3hBglHdbnM2MTb5cHTF.png
                    $cover = str_replace('/storage/','',$lesson->cover_img);
                    //删除public目录下的指定文件
                    Storage::disk('public')->delete($cover);
                }
               
            }
            if($form_data['video_address'] != $lesson->video_address){
                if(file_exitst('.'.$lesson->video_address)){//在'/' 的前面加 .  才能找得到当前的文件 ==./  当前目录下找
                    $video = str_replace('/storage/','',$lesson->video_address);
                    //删除public目录下的指定文件
                    Storage::disk('public')->delete($video);
                }
                
            }
            //上传的教师id是一个数组 存储时以json数据存储
            $form_data['teacher_ids'] = json_encode($form_data['teachers']);
            //修改数据
            $lesson->update($form_data);
            return ['success'=>true];
        }else{
            //校验不通过
            //将错误信息一块输出 （详见辅助函数）
            $errorInfo = collect($validator->messages())->implode('0','|');
            // $errorInfo = $validator->messages();
            return ['success'=>false,'errorinfo'=>$errorInfo];
        }
    }


    return view('admin.lesson.edit',compact('lesson','course','teacher'));
}

//删除课时信息
public function delete(Request $request,Lesson $lesson){

    if($request->isMethod('post')){
        $res = $lesson->delete();//返回删除的条数
        if($res){
            return ['success'=>true];
        }else{
            return ['success'=>false];  
        }
        exit;
    }
}

//恢复软删除的数据展示

public function restore(Request $request){
    if($request->isMethod('post')){
        $start = $request->input('start');
        $len   = $request->input('length');
        $n     = $request->input('order.0.column');//排序的列
        $orderfield= $request->input('columns.'.$n.'.data');//排序的字段
        $order = $request->input('order.0.dir');//desc|asc
        $search= $request->input('search.value');//搜索的关键字
        $res = Lesson::onlyTrashed()
            ->offset($start)
            ->limit($len)
            ->orderBy($orderfield,$order)
            ->where('lesson_name','like',"%$search%")
            ->with(['course'=>function($c){
                $c->with('profession');
            }])
        ->get();
        $cnt = Lesson::onlyTrashed()->count();
        $data = [
        'draw'=>$request->input('draw'),
        'recordsTotal'=>$cnt,
        'recordsFiltered'=>$cnt,
        'data'=>$res,
        ];
        return $data;
    }
    


    return view('admin.lesson.restore');
}
//恢复单条数据
public function restoreOne(Request $request,$id){
    if($request->isMethod('post')){

        $res = (Lesson::withTrashed()->where('lesson_id',$id)->restore());

        if($res){
            return ['success'=>true];
        }else{
            return ['success'=>false];
        }
    }
}
}

